import requests
from requests.adapters import HTTPAdapter
import os
import shutil
from config.architecture import singleton

@singleton
class Download(object):

    def download_remote_local(self, url, targetFilePath):
        if url.startswith('http'):
            self.download_remote_file_path(url, targetFilePath)
        else:
            self.download_local_file_path(url, targetFilePath)

    def download_remote_local_to_parent(self, url, targetParentPath):
        if url.startswith('http'):
            self.download_remote_parent_path(url, targetParentPath)
        else:
            self.download_local_parent_path(url, targetParentPath)

    @staticmethod
    def download_remote_parent_path(url, targetParentPath, chunk_size=2048):
        isExists = os.path.exists(targetParentPath)
        if not isExists:
            os.makedirs(targetParentPath, exist_ok=True)
        fileName = os.path.basename(url).split('?')[0]
        file_path = os.path.join(targetParentPath, fileName)
        s = requests.Session()
        s.mount('http://', HTTPAdapter(max_retries=10))
        r = s.get(url, stream=True, verify=False, timeout=30)
        with open(file_path, 'wb') as fd:
            for chunk in r.iter_content(chunk_size):
                fd.write(chunk)
        return file_path

    @staticmethod
    def download_remote_file_path(url, targetFilePath, chunk_size=2048):
        parentPath = os.path.dirname(targetFilePath)
        isExists = os.path.exists(parentPath)
        if not isExists:
            os.makedirs(parentPath, exist_ok=True)
        s = requests.Session()
        s.mount('http://', HTTPAdapter(max_retries=10))
        r = s.get(url, stream=True, verify=False, timeout=30)
        with open(targetFilePath, 'wb') as fd:
            for chunk in r.iter_content(chunk_size):
                fd.write(chunk)

    @staticmethod
    def download_local_parent_path(url, targetParentPath):
        isExists = os.path.exists(targetParentPath)
        if not isExists:
            os.makedirs(targetParentPath, exist_ok=True)
        fileName = os.path.basename(url).split('?')[0]
        file_path = os.path.join(targetParentPath, fileName)
        shutil.copyfile(url, file_path)
        return file_path

    @staticmethod
    def download_local_file_path(url, targetFilePath, chunk_size=2048):
        parentPath = os.path.dirname(targetFilePath)
        isExists = os.path.exists(parentPath)
        if not isExists:
            os.makedirs(parentPath, exist_ok=True)
        shutil.copyfile(url, targetFilePath)
